'use strict';

var myapp = angular.module('myApp', ['guthub.services', 'guthub.directives',
    'ngFileUpload', 'ngResource', 'ui.bootstrap', 'ngRoute', 'ngAnimate', 'imageCropper'
]);

myapp.config(['$routeProvider', function($routeProvider) {
    $routeProvider.
    when('/', {
        controller: 'ListCtrl',
        resolve: {
            patients: ["MultiPatientLoader", function(MultiPatientLoader) {
                return MultiPatientLoader();
            }]
        },
        templateUrl: 'views/mlist.html'
    }).when('/new', {
        controller: 'NewCtrl',
        templateUrl: 'views/patientBasicForm.html'
    }).when('/view/:patientId', {
        controller: 'ViewCtrl',
        resolve: {
            patient: ["PatientLoader", function(PatientLoader) {
                return PatientLoader();
            }],
            photos: ["MultiPhotoLoader", function(MultiPhotoLoader) {
                return MultiPhotoLoader();
            }],
        },
        templateUrl: 'views/viewPatient.html'
    }).when('/view/photo/:patientId', {
        controller: 'UploadCtrl',
        resolve: {
            patient: ["PatientLoader", function(PatientLoader) {
                return PatientLoader();
            }]
        },
        templateUrl: 'views/photoUpload.html'
    }).otherwise({
        redirectTo: '/'
    });
}]);
/***********************************************************************************************************************************/
myapp.controller('BannerCtrl', ['$scope', '$location', '$http',
    function($scope, $location, $http) {
        $http.get('/apps/services/auth/currentuser')
            .success(function(data, status, headers, config) {
                $scope.user = data;
            });

    }
]);

myapp.controller('RegesterCtrl',['$scope', '$location', '$http',
    function($scope, $location, $http){
      $scope.addUser = function(user){
        $http.post('/apps/services/auth/register',user)
            .success(function(response, status, headers, config) {
                alert(response.msg);
                if(response.msg=="添加新用户成功"){
                  window.location.replace("/apps/index.html");
                }
            }).error(function(data, status, headers, config) {
                console.log(data);
            });
      }
    }

]);

/**********************************************************************************************************************************/
myapp.controller('AlertCtrl', ['$scope', '$modalInstance', '$http',
    function($scope, $modalInstance, $http) {
        $scope.remove = function() {
            $http['delete']('/apps/services/patient/patientid/' + $scope.vm.toDeletePatient.id)
                .success(function(response, status, headers, config) {
                    $scope.vm.patients = response;
                });
            $modalInstance.close();
        };

        $scope.removePicConfirm = function(photo) {
            $http['delete']('/apps/services/photo/' + $scope.vm.toDeletePhoto.patientid + '/' + $scope.vm.toDeletePhoto.id)
                .success(function(response, status, headers, config) {
                    $scope.vm.photos = response;
                });
            $modalInstance.close();
        }

        $scope.removePickerConfirm = function () {
            $scope.vm.mutiPicker.deleteSingleConfirm();
            $modalInstance.close();
        }

        $scope.removePickersConfirm = function () {
            $scope.vm.mutiPicker.deletePickerConfirm();
            $modalInstance.close();
        }

        $scope.uploadConfirm = function() {
            $scope.vm.uploadpics();
            $modalInstance.close();
        }

        $scope.cancel = function() {
            $modalInstance.dismiss('cancel');
        };
    }
]);
/************************************************************************************************************************************/
myapp.controller('ListCtrl', ['$scope', 'patients', '$http', '$location', '$modal',
    function($scope, patients, $http, $location, $modal) {

        var vm = $scope.vm = {};
        vm.patients = patients;

        vm.in = 0;
        vm.out = 0;
        vm.page = {
            size: 10,
            index: 1
        };

        $scope.$watch('vm.patients', function() {
            vm.in = 0;
            vm.out = 0;
            vm.patients.forEach(function(row) {
                if (row.treatcondition == "结束治疗") {
                    vm.out++;
                }
                if (row.treatcondition == "进入治疗") {
                    vm.in++;
                }
            })
        }, true);

        $scope.open = function(patient) {
            vm.toDeletePatient = patient;
            vm.modalInstance = $modal.open({
                templateUrl: 'Alert.html',
                controller: 'AlertCtrl',
                scope: $scope
            });
        };

        $scope.sorttime = 0;
        $scope.psort = function(type) {
            $scope.sorttime = $scope.sorttime + 1;
            if ($scope.sorttime != 1) {
                $scope.sorttime = 0;
                $scope.order = "";
            } else {
                $scope.order = type;
            }
        }

        $scope.addnew = function() {
            $location.path('/new');
        };

    }
]);

/*************************************************************************************************************************************/
myapp.controller('NewCtrl', ['$scope', '$location', 'Patient','$http',
    function($scope, $location, Patient,$http) {
        $scope.patient = new Patient({});
        $scope.chooseother = false;
        var selectedSymptoms = [];

        var getSymptoms = function() {
            var Symptoms = null;
            if (selectedSymptoms.length != 0) {
                Symptoms = selectedSymptoms.join(",")
            }
            if ($scope.chooseother && Symptoms != null && typeof($scope.othersymptom) != "undefined") {
                Symptoms = $scope.othersymptom + "," + Symptoms;
            }
            if ($scope.chooseother && Symptoms == null && typeof($scope.othersymptom) != "undefined") {
                Symptoms = $scope.othersymptom;
            }
            return Symptoms;
        }

        $scope.save = function() {
            $scope.patient.clinicalcondition = getSymptoms();
            // $scope.patient.$save(function(patient) {
            //     $location.path('/view/' + patient.patientid);
            // });

            $http.post('/apps/services/patient/patientid',$scope.patient)
                .success(function(response, status, headers, config) {
                    alert(response.msg);
                    if(response.msg=="添加成功"){
                      $location.path('/view/' + $scope.patient.patientid);
                    }
                }).error(function(data, status, headers, config) {
                    console.log(data);
                });

        };

        $scope.updateSelection = function($event, symptom) {
            var checkbox = $event.target;
            var action = (checkbox.checked ? 'add' : 'remove');
            if (action == 'add' && selectedSymptoms.indexOf(symptom) == -1) {
                selectedSymptoms.push(symptom);
            }
            if (action == 'remove' && selectedSymptoms.indexOf(symptom) != -1) {
                var idx = selectedSymptoms.indexOf(symptom);
                selectedSymptoms.splice(idx, 1);
            }
        }

        $scope.otherSymptom = function($event) {
            var checkbox = $event.target;
            var action = (checkbox.checked ? 'add' : 'remove');
            if (action == 'add') {
                $scope.chooseother = true;
            }
            if (action == 'remove') {
                $scope.chooseother = false;
            }
        }
    }
]);

/**************************************************************************************************************************************/
myapp.controller('ViewCtrl', ['$scope', '$location', 'patient', 'photos', '$http', 'Upload', '$modal','filterFilter',
    function($scope, $location, patient, photos, $http, Upload, $modal,filterFilter) {
        var vm = $scope.vm = {};
        vm.patient = patient;
        vm.photos = photos;
        $scope.currentstate = null;
        $scope.currentphotodate = null;

        //console.log(vm.photos);

        vm.initMethods = {
            getDisplayBoards: function(photos) {
                var correctList = [];
                var displayBoards = [];
                for (var i = 0; i < photos.length; i++) {
                    if (correctList.indexOf(photos[i].photodate) == -1) {
                        correctList.push(photos[i].photodate);
                        displayBoards.push({
                            recordDate: photos[i].photodate,
                            treatTime: this.getTreatTime(photos[0].photodate, photos[i].photodate),
                            treatState: this.getTreatState(photos[i].photostate),
                            treatStateEn: photos[i].photostate,
                            picked:false
                        });
                    }
                }
                return displayBoards;
            }, //**********************获取所有去掉重复拍摄日期，初始化展示列表属性********************************
            getTreatTime: function(startDate, endDate) {
                var startTime = Date.parse(startDate);
                var endTime = Date.parse(endDate);
                var days = parseInt(Math.abs(endTime - startTime) / 1000 / 60 / 60 / 24);
                var years = Math.floor(days / 365);
                var months = Math.floor(days / 30);
                if (years > 0) {
                    return "开始治疗后" + years + "年";
                } else if (months > 0 && years == 0) {
                    return "开始治疗后" + months + "个月";
                } else {
                    return "开始治疗后" + days + "天";
                }
            }, //**********************获取已经治疗的时间**********************************************
            getTreatState: function(state) {
                    switch (state) {
                        case 'before':
                            return '治疗前期';
                            break;
                        case 'middle':
                            return '治疗中期';
                            break;
                        case 'after':
                            return '治疗后期';
                            break;
                        default:
                            return '未知时期';
                    }
                } //************************将治疗时期转化为中文显示*****************************************
        }

        $scope.$watch('vm.photos', function() {
            vm.displayBoards = vm.initMethods.getDisplayBoards(vm.photos);
            vm.currentHeads = filterFilter(vm.photos,{phototype:'head',photodate:$scope.currentphotodate});
            vm.currenTeeth = filterFilter(vm.photos,{phototype:'teeth',photodate:$scope.currentphotodate});
            vm.currentXimgs = filterFilter(vm.photos,{phototype:'ximg',photodate:$scope.currentphotodate});
        }, true);

/***************************时间轴多选模块***********************************************/
        vm.mutiPicker={
          pickStamp:false,
          pickStarter:function(){
            this.pickStamp = true;
          },
          pickEnder:function(){
            this.pickStamp = false;
          },
          pickAll:function(pickstate){
            vm.displayBoards.forEach(function(row){
              row.picked = pickstate;
            });
          },
          dateListCheck:function () {
            var pickList = [];
            vm.displayBoards.forEach(function (row) {
              if (row.picked) {
                pickList.push(row.recordDate)
              }
            });
            return pickList;
          },
          deleteSinglePicker:function(date){
            vm.mutiPicker.toDeleteDate = date;
            var modalInstance = $modal.open({
                templateUrl: 'removePickerAlert.html',
                controller: 'AlertCtrl',
                size: 'sm',
                scope: $scope
            });
          },
          deleteSingleConfirm:function(){
            $http['delete']('/apps/services/photo/multidelete/date/'+vm.patient.patientid+'/'+this.toDeleteDate)
            .success(function(response, status, headers, config) {
                $scope.vm.photos = response;
                alert('删除成功！');
            }).error(function(data, status, headers, config) {
                alert('删除失败！');
            });
          },
          deletePicker:function () {
            this.toDeleteDateList = this.dateListCheck();
            if (this.toDeleteDateList.length>0) {
              var modalInstance = $modal.open({
                  templateUrl: 'removePickersAlert.html',
                  controller: 'AlertCtrl',
                  size: 'sm',
                  scope: $scope
              });

            }else {
                alert('您还没有选择任何一组日期！');
            }
          },
          deletePickerConfirm:function () {
            console.log(this.toDeleteDateList);
            $http['delete']('/apps/services/photo/multidelete/dates/'+vm.patient.patientid,{params: {datelist:this.toDeleteDateList}})
            .success(function(response, status, headers, config) {
                $scope.vm.photos = response;
                alert('删除成功！');
            }).error(function(data, status, headers, config) {
                alert('删除失败！');
            });
          },
          downloadPicker:function () {
            var downList = this.dateListCheck();
            if (downList.length>0) {
              console.log(downList);
            }else {
                alert('您还没有选择任何一组日期！');
            }
          }
        };


/***********************照片编辑模块****************************************************/
        vm.cropper = {
            editPicture: null,
            cropperWidth: 0,
            cropperHeight: 0,
            ratioBoards: [{
                width: 225,
                height: 340
            }, {
                width: 340,
                height: 225
            }, {
                width: 350,
                height: 340
            }],
            cropperRatio: function(type) {
                switch (type) {
                    case 'head':
                        this.cropperWidth = this.ratioBoards[0].width;
                        this.cropperHeight = this.ratioBoards[0].height;
                        break;
                    case 'teeth':
                        this.cropperWidth = this.ratioBoards[1].width;
                        this.cropperHeight = this.ratioBoards[1].height;
                        break;
                    case 'ximg':
                        this.cropperWidth = this.ratioBoards[2].width;
                        this.cropperHeight = this.ratioBoards[2].height;
                        break;
                    default:
                        this.cropperWidth = 200;
                        this.cropperHeight = 200;
                }
            },
            imageUrl: null,
            editCroper: function(photo) {
                this.editPicture = photo;
                this.imageUrl = 'images' + photo.photourl;
                this.cropperRatio(photo.phototype);
                var modalInstance = $modal.open({
                    templateUrl: 'editPicture.html',
                    controller: 'AlertCtrl',
                    //size: 'lg',
                    scope: $scope
                });
            },
            myButtonLabels: {
                rotateLeft: '左转',
                rotateRight: ' 右转 ',
                zoomIn: ' <span class="glyphicon glyphicon-zoom-in"></span> ',
                zoomOut: ' <span class="glyphicon glyphicon-zoom-out"></span> ',
                fit: ' 相片误差复位 ',
                crop: ' <span class="glyphicon glyphicon-floppy-disk"></span> '
            },
            updateResultImage: function(base64) {
                vm.resultImage = base64;
                $http.post('/apps/services/photo/edit/' + vm.cropper.editPicture.patientid + "/" + vm.cropper.editPicture.id, vm.resultImage)
                    .success(function(response, status, headers, config) {
                        $scope.vm.photos = response;
                    }).error(function(data, status, headers, config) {
                        console.log(data + status + config);
                    });
            }
        };

/************************上传封面函数*************************************************/
        $scope.uploadnow = true;
        $scope.cover = {
            file: null,
            progress: 0
        };

        $scope.uploadcover = function(cover) {
            if (cover.file != null) {
                Upload.upload({
                    url: '/apps/services/photo/upload/cover',
                    file: cover.file,
                    fields: {
                        'patientid': vm.patient.patientid,
                    }
                }).progress(function(evt) {
                    cover.progress = parseInt(100.0 * evt.loaded / evt.total);
                }).success(function(data, status, headers, config) {

                }).error(function(data, status, headers, config) {
                    console.log('error status: ' + status);
                });
                $scope.uploadnow = false;
            } else {
                alert("请点击图片上传照片");
            }
        }


        $scope.checkphotos = function(state, date) {
            $scope.currentstate = state;
            $scope.currentphotodate = date;
            vm.currentHeads = filterFilter(vm.photos,{phototype:'head',photodate:$scope.currentphotodate});
            vm.currenTeeth = filterFilter(vm.photos,{phototype:'teeth',photodate:$scope.currentphotodate});
            vm.currentXimgs = filterFilter(vm.photos,{phototype:'ximg',photodate:$scope.currentphotodate});
        }

        $scope.endTreat = function() {
            //var condition = 'abc';
            console.log(vm.patient.treatcondition);
            vm.patient.treatcondition = '结束治疗';
            vm.patient.$save(function() {
                $location.path('/');
            });
        }

        $scope.removeAlert = function(photo) {
            vm.toDeletePhoto = photo;
            var modalInstance = $modal.open({
                templateUrl: 'removeAlert.html',
                controller: 'AlertCtrl',
                scope: $scope
            });
        };

        $scope.uploadBoard = function(photo) {
            vm.toDeletePhoto = photo;
            var modalInstance = $modal.open({
                templateUrl: 'views/photoUpload.html',
                controller: 'UploadCtrl',
                size: 'lg',
                scope: $scope
            });
        };
    }
]);

/**********************************************************************************************************************************************/
myapp.controller('UploadCtrl', ['$scope', 'Upload', '$location', '$filter', '$modal', '$modalInstance',
    function($scope, Upload, $location, $filter, $modal, $modalInstance) {
        var vm = $scope.vm;
        $scope.patient = vm.patient;

        var stateconvter = [{
            status: "治疗前期",
            value: "before"
        }, {
            status: "治疗中期",
            value: "middle"
        }, {
            status: "治疗后期",
            value: "after"
        }];



        vm.currentDate = $filter('date')(new Date(), 'yyyy-MM-dd');
        vm.currentstate = null;
        vm.state = null;
        vm.treatDate = null;

        $scope.headphs = [{
            imageFile: null,
            imageSrc: "img/1.jpg",
            photoId: "1",
            photostate: "head",
            phototype: "head",
            progress: 0
        }, {
            imageFile: null,
            imageSrc: "img/2.jpg",
            photoId: "2",
            photostate: "head",
            phototype: "head",
            progress: 0
        }, {
            imageFile: null,
            imageSrc: "img/3.jpg",
            photoId: "3",
            photostate: "head",
            phototype: "head",
            progress: 0
        }];

        $scope.toothphs = [{
                imageFile: null,
                imageSrc: "img/4.jpg",
                photoId: "4",
                photostate: "before",
                phototype: "teeth",
                progress: 0
            }, {
                imageFile: null,
                imageSrc: "img/5.jpg",
                photoId: "5",
                photostate: "before",
                phototype: "teeth",
                progress: 0
            }, {
                imageFile: null,
                imageSrc: "img/6.jpg",
                photoId: "6",
                photostate: "before",
                phototype: "teeth",
                progress: 0
            }, {
                imageFile: null,
                imageSrc: "img/7.jpg",
                photoId: "7",
                photostate: "before",
                phototype: "teeth",
                progress: 0
            }, {
                imageFile: null,
                imageSrc: "img/8.jpg",
                photoId: "8",
                photostate: "before",
                phototype: "teeth",
                progress: 0
            }

        ];

        $scope.ximgs = [{
            imageFile: null,
            imageSrc: "img/9.jpg",
            photoId: "9",
            photostate: "before",
            phototype: "ximg",
            progress: 0
        }, {
            imageFile: null,
            imageSrc: "img/10.jpg",
            photoId: "10",
            photostate: "before",
            phototype: "ximg",
            progress: 0
        }];

        $scope.changestate = function(state) {
            vm.currentstate = stateconvter[state].status;
            vm.state = stateconvter[state].value;

        };

        $scope.addhead = function(file) {
            if (file != null) {
                $scope.headphs.push({
                    imageFile: file,
                    imageSrc: "",
                    photoId: $scope.headphs.length + 1,
                    photostate: "before",
                    phototype: "head",
                    progress: 0
                });
            }
        };

        $scope.addteeth = function(file) {
            if (file != null) {
                $scope.toothphs.push({
                    imageFile: file,
                    imageSrc: "",
                    photoId: $scope.toothphs.length + 1,
                    photostate: "before",
                    phototype: "teeth",
                    progress: 0
                });
            }
        };

        $scope.addximg = function(file) {
            if (file != null) {
                $scope.ximgs.push({
                    imageFile: file,
                    imageSrc: "",
                    photoId: $scope.ximgs.length + 1,
                    photostate: "before",
                    phototype: "ximg",
                    progress: 0
                });
            }
        };

        vm.uploadProcess = 0;
        vm.finishedProcess = 0;
        vm.uploadpics = function() {
            vm.uploadPocess = 'pocessing';
            $scope.headphs.forEach(function(item) {
                if (item.imageFile != null) {
                    vm.uploadProcess++;
                    item.photostate = vm.state;
                    vm.uploadFile(item);
                }
            });
            $scope.toothphs.forEach(function(item) {
                if (item.imageFile != null) {
                    vm.uploadProcess++;
                    item.photostate = vm.state;
                    vm.uploadFile(item);
                }
            });
            $scope.ximgs.forEach(function(item) {
                if (item.imageFile != null) {
                    vm.uploadProcess++;
                    item.photostate = vm.state;
                    vm.uploadFile(item);
                }
            });
        };

        $scope.uploadAlert = function() {
            var modalInstance = $modal.open({
                templateUrl: 'uploadAlert.html',
                controller: 'AlertCtrl',
                size: 'sm',
                scope: $scope
            });
        }

        vm.uploadFile = function(item) {
            vm.treatDate = $filter('date')(vm.treatDate, 'yyyy-MM-dd');
            Upload.upload({
                url: '/apps/services/photo/upload',
                file: item.imageFile,
                fields: {
                    'phototype': item.phototype,
                    'photostate': item.photostate,
                    'photodate': vm.treatDate,
                    'patientid': $scope.patient.patientid
                }
            }).progress(function(evt) {
                item.progress = parseInt(100.0 * evt.loaded / evt.total);
                console.log('progress: ' + item.progress + '% ' + evt.config.file.name);
            }).success(function(data, status, headers, config) {
                vm.finishedProcess++;
                if (vm.finishedProcess==vm.uploadProcess) {
                  vm.finishedProcess=0;
                  vm.uploadProcess=0;
                  alert('上传成功！')
                  $scope.vm.photos = data;
                  vm.uploadPocess = 'done';
                }

            }).error(function(data, status, headers, config) {
                console.log(data);
                console.log('error status: ' + status);
                alert("照片"+item.imageFile.name+"上传失败，可能是由于服务器较忙，请重新上传");
            });
        }

        $scope.cancel = function() {
            $modalInstance.dismiss('cancel');
            vm.uploadPocess = '';
        };

    }
]);

/************************************************************************************************************************************************/





myapp.filter('paging', function() {
    return function(patients, index, pageSize) {
        if (!patients)
            return [];

        var offset = (index - 1) * pageSize;
        return patients.slice(offset, offset + pageSize);
    };
});

myapp.filter('size', function() {
    return function(patients) {
        if (!patients)
            return 0;

        return patients.length || 0;
    };
});

myapp.filter('head', function() {
    return function(photos) {
        if (!patients)
            return 0;

        return patients.length || 0;
    };
});
